<template>
  <div class="setting-body">
    <el-form ref="form" :model="form" size="small" label-width="120px">
      <div class="custom-tips">
        查询项设置
        <div class="button-add">
          <el-button
            type="text"
            icon="el-icon-plus"
            @click="doAdd"
          >新增</el-button>
        </div>
      </div>
      <el-row :gutter="20" style="margin-top: 10px">
        <draggable v-model="form.query" animation="300" @end="clone">
          <el-col
            v-for="(item, index) in form.query"
            :key="'query-' + index"
            :span="24"
          >
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item
                  label="查询项名称"
                  :prop="'query.' + index + '.label'"
                  :rules="[
                    {
                      required: true,
                      message: '请输入查询项名称',
                      trigger: 'blur'
                    }
                  ]"
                >
                  <el-input v-model="item.label" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="查询项"
                  :prop="'query.' + index + '.column'"
                  :rules="[
                    {
                      required: true,
                      message: '请选择查询项',
                      trigger: 'change'
                    }
                  ]"
                >
                  <el-select
                    v-model="item.column"
                    clearable
                    placeholder="请选择查询项"
                  >
                    <el-option
                      v-for="obj in queryList"
                      :key="obj.id"
                      :label="obj.name"
                      :value="obj.code"
                    />
                  </el-select>
                </el-form-item>
                <el-col :span="24" style="text-align: right">
                  <el-button
                    type="text"
                    icon="el-icon-delete"
                    size="mini"
                    @click="toDelete(item)"
                  >删除</el-button>
                </el-col>
              </el-col>
            </el-row>
          </el-col>
        </draggable>
      </el-row>
      <div class="custom-tips">
        详情设置
      </div>
      <el-row :gutter="20" style="margin-top: 10px">
        <el-col :span="12">
          <el-form-item
            label="是否打开详情页"
            prop="isOpenEntity"
            :rules="[
              {
                required: true,
                message: '请选择是否打开详情页',
                trigger: 'change'
              }
            ]"
          >
            <el-radio-group v-model="form.isOpenEntity">
              <el-radio
                v-for="item in status"
                :key="item.id"
                :label="item.value"
              >{{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.isOpenEntity" :gutter="20" style="margin-top: 10px">
        <el-col :span="12">
          <el-form-item
            label="详情页打开方式"
            prop="entityOpenType"
            :rules="[
              {
                required: true,
                message: '请选择详情页打开方式',
                trigger: 'change'
              }
            ]"
          >
            <el-select
              v-model="form.entityOpenType"
              clearable
              placeholder="请选择详情页打开方式"
            >
              <el-option
                v-for="obj in openType"
                :key="'entity-' + obj.id"
                :label="obj.label"
                :value="obj.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="form.entityOpenType === 1" :span="24">
          <el-form-item
            label="地址参数"
            prop="entityUrl"
            :rules="[
              { required: true, message: '请选择地址参数', trigger: 'change' }
            ]"
          >
            <el-select
              v-model="form.entityUrl"
              clearable
              placeholder="请选择地址参数"
            >
              <el-option
                v-for="obj in jxx"
                :key="obj"
                :label="obj"
                :value="obj"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="form.entityOpenType === 3" :span="12">
          <el-form-item
            label="详情模版"
            prop="entityTemplateId"
            :rules="[
              { required: true, message: '请选择地址参数', trigger: 'change' }
            ]"
          >
            <el-select
              v-model="form.entityTemplateId"
              clearable
              placeholder="请选择地址参数"
              @change="entityChange"
            >
              <el-option
                v-for="obj in entityTemp"
                :key="obj.id"
                :label="obj.name"
                :value="obj.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div
        v-if="form.isOpenEntity === true && form.entityOpenType === 2"
        class="custom-tips"
      >
        参数设置
        <div class="button-add">
          <el-button
            type="text"
            icon="el-icon-plus"
            @click="doAddParams"
          >新增</el-button>
        </div>
      </div>
      <el-row
        v-if="form.isOpenEntity === true && form.entityOpenType === 2"
        :gutter="20"
        style="margin-top: 10px"
      >
        <el-col :span="24">
          <el-row
            v-for="(item, index) in form.params"
            :key="'pp-' + index"
            :gutter="20"
          >
            <el-col :span="10">
              <el-form-item
                label="参数"
                :prop="'params.' + index + '.code'"
                :rules="[
                  { required: true, message: '请输入参数名称', trigger: 'blur' }
                ]"
              >
                <el-input
                  v-model="item.code"
                  clearable
                  placeholder="请输入参数名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item
                label="请选择关联字段"
                :prop="'params.' + index + '.column'"
                :rules="[
                  {
                    required: true,
                    message: '请选择关联字段',
                    trigger: 'change'
                  }
                ]"
              >
                <el-select
                  v-model="item.column"
                  clearable
                  placeholder="请选择关联字段"
                >
                  <el-option
                    v-for="obj in jxx"
                    :key="obj"
                    :label="obj"
                    :value="obj"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4" style="text-align: center">
              <el-button
                type="text"
                icon="el-icon-delete"
                size="mini"
                @click="removeParams(item)"
              >删除</el-button>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="地址参数"
            prop="entityUrl"
            :rules="[
              { required: true, message: '请输入地址参数', trigger: 'blur' }
            ]"
          >
            <el-input
              v-model="form.entityUrl"
              clearable
              placeholder="请输入打开地址，地址中参数请用${}包裹"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row
        v-if="form.entityOpenType === 3 && form.isOpenEntity === true"
        :gutter="20"
        :span="12"
        style="margin-top: 10px"
      >
        <el-col
          v-for="(item, index) in form.entityParams"
          :key="'ee-' + index"
          :span="12"
        >
          <el-form-item
            :label="item.name"
            :prop="'entityParams.' + index + '.value'"
            :rules="[
              { required: true, message: '请选择关联字段', trigger: 'change' }
            ]"
          >
            <el-select
              v-model="item.value"
              clearable
              placeholder="请选择关联字段"
            >
              <el-option
                v-for="obj in jxx"
                :key="obj"
                :label="obj"
                :value="obj"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="custom-button">
      <el-button type="text" @click="close">取消</el-button>
      <el-button
        :loading="loading"
        type="primary"
        @click="save('form')"
      >确认</el-button>
    </div>
  </div>
</template>
<script>
import draggable from 'vuedraggable';
import { updateObject } from '@/api/portal/manager/columnTemp';
import {
  queryAllDataBySystem,
  queryAllDataSource,
  queryAllSystemSys
} from '@/api/portal/manager/analysis';
import { queryAllSjx } from '@/api/mobile/data';
import { queryAll } from '@/api/portal/manager/entityTemp';
import { queryAllServiceParams } from '@/api/portal/manager/setting/index';
export default {
  name: 'OfficeHallAppV1',
  components: { draggable },
  props: {
    data: {
      type: Object,
      default: function() {
        return {};
      }
    }
  },
  data() {
    return {
      loading: false,
      jxx: [],
      dataList: [],
      dataSource: [],
      queryList: [],
      entityTemp: [],
      status: [
        { id: 0, value: false, label: '否' },
        { id: 1, value: true, label: '是' }
      ],
      openType: [
        { id: 1, value: 1, label: '地址参数' },
        { id: 2, value: 2, label: '地址传参' },
        { id: 3, value: 3, label: '详情模版' }
      ],
      form: {
        size: 1,
        row: 1,
        isOpenMore: false,
        gdxsx: false,
        xsnr: [],
        query: [],
        image: '',
        title: '',
        entity: '',
        url: '',
        id: '',
        isOpenEntity: false,
        entityTemplateId: null, // 详情页模版编号
        entityParams: [], // 详情参数设置
        params: [],
        entityOpenType: null, // 详情页打开方式
        entityUrl: '', // 详情地址
        entityTemp: null
      }
    };
  },
  watch: {
    data: {
      handler(newName, oldName) {
        if (undefined !== newName && newName.sjlx !== null) {
          if (newName.sjlx === 1) {
            this.initDataJxx();
          } else if (newName.sjlx === 2) {
            this.initSystemJxx();
          }
          if (
            undefined !== newName.pzx &&
            newName.pzx !== '' &&
            newName.pzx !== null
          ) {
            this.form = JSON.parse(newName.pzx);
            if (this.form.query === undefined) {
              this.form.query = [];
            }
          }
          if (newName.id !== null) {
            this.initDataList();
          }
        }
      },
      immediate: true, // 父组件第一次传值时，执行handler，false则第一次不执行
      deep: false // formType为对象时，设置为true，此属性监听对象发生变化
    }
  },
  created() {
    document.body.ondrop = function(event) {
      event.preventDefault();
      event.stopPropagation();
    };
    this.initDataSource();
    this.initAllTemp();
    this.initQuery();
  },
  methods: {
    stateChange() {
      if (this.form.gdxsx) {
        this.initDataList();
      } else {
        this.dataList = [];
      }
    },
    entityChange(data) {
      const entity = this.entityTemp.filter(item => {
        if (item.id === data) {
          return item;
        }
      });
      if (entity !== undefined && entity !== null && entity.length > 0) {
        const param = entity[0].params;
        this.form.entityTemp = entity[0];
        this.form.entityParams = [];
        this.form.entityParams.push({
          name: '服务编号',
          code: 'id',
          valueType: 6,
          test: false,
          testValue: null
        });
        if (undefined !== param && param !== null) {
          const newParams = JSON.parse(param).map(item => {
            item.test = false;
            item.value = '';
            return item;
          });
          newParams.forEach(item => {
            this.form.entityParams.push(item);
          });
        } else {
          this.form.entityParams = [];
          this.form.entityParams.push({
            name: '服务编号',
            code: 'id',
            valueType: 6,
            test: false,
            testValue: null
          });
        }
      }
    },
    initAllTemp() {
      queryAll()
        .then(res => {
          const { data } = res;
          this.entityTemp = data.data;
        })
        .catch(() => {
          this.entityTemp = [];
        });
    },
    removeParams(item) {
      const index = this.form.params.indexOf(item);
      if (index !== -1) {
        this.form.params.splice(index, 1);
      }
    },
    doAddParams() {
      const item = { code: '', column: '' };
      if (this.form.params === undefined) {
        this.form.params = [];
      }
      this.form.params.push(item);
    },
    save() {
      this.loading = true;
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.data.pzx = JSON.stringify(this.form);
          updateObject(this.data)
            .then(res => {
              this.close();
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          this.loading = false;
        }
      });
    },
    close() {
      this.loading = false;
      Object.assign(this.$data.form, this.$options.data.call(this).form);
      this.dialogFormVisible = false;
      this.$emit('fetch-data');
    },
    initDataJxx() {
      queryAllDataSource({ id: this.data.sjx }).then(res => {
        const { data } = res;
        this.jxx = data;
      });
    },
    initSystemJxx() {
      queryAllDataBySystem({ id: this.data.sjx }).then(res => {
        const { data } = res;
        this.jxx = data;
      });
    },
    initDataList() {
      queryAllSystemSys({ cid: this.data.id, page: 1, size: 2000, obj: true })
        .then(res => {
          const { data } = res;
          if (undefined !== data && data !== null) {
            this.dataList = data.data;
          } else {
            this.dataList = [];
          }
        })
        .catch(() => {
          this.dataList = [];
        });
    },
    initDataSource() {
      queryAllSjx().then(res => {
        const { data } = res;
        if (undefined !== data && data !== null) {
          this.dataSource = data.data;
        }
      });
    },
    initQuery() {
      queryAllServiceParams()
        .then(res => {
          const { data } = res;
          this.queryList = data;
        })
        .catch(() => {
          this.queryList = [];
        });
    },
    doAdd() {
      const item = { label: '', column: '', type: null, ysf: null, sjx: null };
      this.form.query.push(item);
    },
    toDelete(item) {
      const index = this.form.query.indexOf(item);
      if (index !== -1) {
        this.form.query.splice(index, 1);
      }
    },
    clone() {
      this.form.query = this.form.query.map((item, index) => {
        item.px = index + 1;
        return item;
      });
    }
  }
};
</script>

<style scoped>
.setting-body {
  width: 100%;
}
.custom-tips {
  width: 100%;
  min-height: 40px;
  line-height: 40px;
  text-align: left;
  padding: 8px 16px;
  background-color: #ecf8ff;
  border-radius: 4px;
  border-left: 5px solid #50bfff;
}
.button-add {
  width: 50px;
  height: 40px;
  float: right;
  text-align: center;
  line-height: 40px;
  margin-right: 20px;
}
.custom-button {
  text-align: right;
}
</style>
